package com.example.demo.util;

import com.alibaba.druid.support.json.JSONUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Description:redis操作工具类
 * @create: 2018-07-06 16:53
 **/
@Component
public class RedisUtils implements InitializingBean {
    @Autowired
    private RedisTemplate redisTemplate;

    private ValueOperations valueOperations;

    /**
     * 设置值
     * @param key
     * @param obj
     * @param timeout 超时时间, 单位秒
     */
    public void set(String key, Object obj, long timeout) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String v = null;
        if (obj instanceof String) {
            v = (String) obj;
        } else {
            v = JSONUtils.toJSONString(obj);
        }
        if (timeout == 0) {
            valueOperations.set(key, obj);
        } else {
            valueOperations.set(key, obj, timeout, TimeUnit.SECONDS);
        }
    }

    public void set(String key, Object obj) {
        set(key, obj, 0);
    }

    public Object get(String key) {
        return valueOperations.get(key);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        valueOperations = redisTemplate.opsForValue();
    }
}
